/*
 * (C) Copyright 2012, by Tim Xie.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.superapk.diamond.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * 网络图片缓存工具
 * 
 * @author     Tim Xie [tim.xie2008@gmail.com]
 * @date 2013-1-23
 * 
 */

public class HttpImageCacheUtil {
	
	private final static String LOGTAG = LogUtil.makeLogTag(HttpImageCacheUtil.class);

	/**
	 * 缓存的根目录，根据项目地址更改
	 */
	private final static String CACHE_ROOT_DIR = "/sdcard/diamondcache";
	/**
	 * 图片缓存地址
	 */
	private final static String IMAGE_CACHE_DIR = CACHE_ROOT_DIR + "/76811a6bc7bc5ed5";

	/**
	 * 把一张图片缓存到SDCard
	 * 
	 * @param httpUrl 图片的Url地址
	 * @param fileDatas 图片的数据
	 */
	public static void addCache(final String httpUrl, final byte[] fileDatas) {
		if (httpUrl == null) {
			LogUtil.w("httpUrl must be not null.");
			return;
		}
		if(fileDatas == null){
			LogUtil.w("fileDatas must be not null.");
			return;
		}
		// 使用线程写入
		new Thread() {
			public void run() {
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断SDcard是否可用
					try {
						String fileName = getMd5FileName(httpUrl);
						if (fileName == null || fileName.equals(""))
							return;
						// 判断根目录是否已经建好
						File rootFile = new File(CACHE_ROOT_DIR);
						if (!rootFile.exists())
							rootFile.mkdir();
						File imageRootFile = new File(IMAGE_CACHE_DIR);
						if (!imageRootFile.exists())
							imageRootFile.mkdir();
						File file = new File(IMAGE_CACHE_DIR, fileName);
						if (file.exists())// 已存在，删除
							file.delete();
						file.createNewFile();
						FileOutputStream fos = new FileOutputStream(file);
						fos.write(fileDatas);
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	/**
	 * 获取SdCard的图片缓存
	 * @param context
	 * @param httpUrl
	 * @return
	 */
	public static Bitmap getCacheBitmap(Context context, String httpUrl) {
		byte[] cacheDatas = getCacheBitmapData(httpUrl);
		Bitmap tmpBitmap = null;
		if (cacheDatas != null) {
			try {
				// 会根据scale转换Bitmap
				float scale = context.getResources().getDisplayMetrics().density;
				tmpBitmap = BitmapFactory.decodeByteArray(cacheDatas, 0,
						cacheDatas.length);
				int reDensity = (int) (tmpBitmap.getDensity() / scale);
				tmpBitmap.setDensity(reDensity);
			} catch (Exception e) {
				Log.e(LOGTAG, "Decode cache bitmap failed." + e.toString());
			}
		}
		return tmpBitmap;
	}

	/**
	 * 获取一张SDCard的图片缓存数据
	 * 
	 * @param httpUrl
	 * @return
	 */
	public static byte[] getCacheBitmapData(String httpUrl) {
		byte[] fileDatas = null;
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断SDcard是否可用
			try {
				String fileName = getMd5FileName(httpUrl);
				if (fileName == null || fileName.equals(""))
					return null;
				// 判断根目录是否已经建好
				File file = new File(IMAGE_CACHE_DIR, fileName);
				if (file.exists()) {
					FileInputStream fis = new FileInputStream(file);
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte[] buffer = new byte[512];
					int read = 0;
					do {
						read = fis.read(buffer);
						if (read > 0) {
							bos.write(buffer, 0, read);
						}
					} while (read != -1);
					fileDatas = bos.toByteArray();
					bos.close();
					fis.close();

				}
			} catch (Exception e) {
				Log.e(LOGTAG, e.toString());
			}
			return fileDatas;
		} else {
			return fileDatas;
		}
	}

	/**
	 * 根据图片的url生成MD5文件名
	 */
	private static String getMd5FileName(String httpUrl) {
		if (httpUrl != null) {
			String md5HttpUrl = MD5Util.getMD5Encoding(httpUrl);
			return md5HttpUrl;
		}
		return null;
	}

}
